package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.Dlhlsensor;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Dlhlhistory;
import com.example.onlinemonitoring.serviceImpl.DlhlsensorServiceImpl;
import com.example.onlinemonitoring.model.Dljfsensor;
import com.example.onlinemonitoring.model.Dljfhistory;
import com.example.onlinemonitoring.serviceImpl.DljfsensorServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;
import java.text.ParseException;
import java.util.Date;
import java.util.Random;
import java.util.List;
import java.util.ArrayList;

/**
 * 电缆环流
 */
@Service("dlhlCom")
@Scope("prototype")
public class DlhlCom extends CommPortManager {
    @Autowired
    private DlhlsensorServiceImpl dlhlserviceimpl;
    @Autowired
    private DljfsensorServiceImpl dljfsensorService;
    // private float dc = 1.42f;
    private float dc[] = new float[255];

    @Override
    public void receiveData(String str) {
        try {
            str = str.toUpperCase();
            // "7E01804000080001000200030005CHKSUM"
            setText(str);
            if (str.length() == 45 && "7F".equals(str.substring(0, 2))) {
                return;
            }

            receiveDataHl(str);
            receiveDataJf(str);
            if (ad.getBrand().equals("1"))
                dlhlVertype = 1;
        } catch (Exception ex) {
            ex.printStackTrace();
            setText("从设备返回的数据有误！请检查串口！");
        }
    }

    public void receiveDataHl(String str) {
        // 地址解析addr
        String addrstr = str.substring(2, 4);
        // 转地址
        Integer addrint = parseHex4(addrstr);
        reSend[addrint] = 0;
        addrindex++;
        // dlhlserviceimpl.setstatus(0,addrint);
        reSend[parseHex4(addrstr)] = 0;
        // 设备类型编码
        String s_cid1 = str.substring(4, 6);
        String s_cid2 = str.substring(6, 8);
        // 请求返回状态00(正常）01 CHKSUM错
        String rtn = str.substring(8, 10);
        Integer startIndex = 12;
        // 判断请求返回，是否电流相关，返回码是否正常
        if ("80".equals(s_cid1) && ("40".equals(s_cid2) || "41".equals(s_cid2)) && "00".equals(rtn)) {
            setText("设备返回数据： 站点号：" + ad.getStationid() + " 设备组：" + ad.getDevicegroup() + " 设备地址：" + addrint);
            // String length = str.substring(12, 14);

            Dlhlsensor dlhlsensor = new Dlhlsensor();
            // 设置设备地址
            dlhlsensor.setStationid(ad.getStationid());
            dlhlsensor.setDevicegroup(ad.getDevicegroup());
            dlhlsensor.setDeviceaddr(addrint);
            // 查询对象
            Dlhlsensor record = dlhlserviceimpl.getModel(dlhlsensor);
            if (record == null) {
                setText("当前数据库无监测点：设备地址" + addrint);
            }
            // String stlyestr = record.getStyle();
            // if((stlyestr==null)||(stlyestr.equals("")))
            // {
            // stlyestr="acurrent|1|A相电流,bcurrent|1|B相电流,ccurrent|1|C相电流,dcurrent|1|负荷电流";
            // record.setStyle(stlyestr);
            // }
            // 获取电流系数
            float agreatevalue = record.getAcurrentcoefficientgreatevalue() == null ? 1f
                    : record.getAcurrentcoefficientgreatevalue();
            float bgreatevalue = record.getBcurrentcoefficientgreatevalue() == null ? 1f
                    : record.getBcurrentcoefficientgreatevalue();
            float cgreatevalue = record.getCcurrentcoefficientgreatevalue() == null ? 1f
                    : record.getCcurrentcoefficientgreatevalue();
            // float a1greatevalue = record.getA1currentcoefficientgreatevalue() == null ?
            // 1f : record.getA1currentcoefficientgreatevalue();
            // float b1greatevalue = record.getB1currentcoefficientgreatevalue() == null ?
            // 1f : record.getB1currentcoefficientgreatevalue();
            // float c1greatevalue = record.getC1currentcoefficientgreatevalue() == null ?
            // 1f : record.getC1currentcoefficientgreatevalue();
            float dgreatevalue = record.getDcurrentcoefficientgreatevalue() == null ? 1f
                    : record.getDcurrentcoefficientgreatevalue();
            float alessvalue = record.getAcurrentcoefficientlessvalue() == null ? 1f
                    : record.getAcurrentcoefficientlessvalue();
            float blessvalue = record.getBcurrentcoefficientlessvalue() == null ? 1f
                    : record.getBcurrentcoefficientlessvalue();
            float clessvalue = record.getCcurrentcoefficientlessvalue() == null ? 1f
                    : record.getCcurrentcoefficientlessvalue();
            // float a1lessvalue = record.getA1currentcoefficientlessvalue() == null ? 1f :
            // record.getA1currentcoefficientlessvalue();
            // float b1lessvalue = record.getB1currentcoefficientlessvalue() == null ? 1f :
            // record.getB1currentcoefficientlessvalue();
            // float c1lessvalue = record.getC1currentcoefficientlessvalue() == null ? 1f :
            // record.getC1currentcoefficientlessvalue();
            float dlessvalue = record.getDcurrentcoefficientlessvalue() == null ? 1f
                    : record.getDcurrentcoefficientlessvalue();

            float lastacurrnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16) / 100f;
            float lastbcurrnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16) / 100f;
            float lastccurrnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16) / 100f;
            float lastdcurrnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16);
            setText("A相电流：" + lastacurrnet + "A" + " B相电流：" + lastbcurrnet + "A" + " C相电流：" + lastccurrnet + "A"
                    + " 负荷电流：" + lastdcurrnet + "A");
            // setText("A1相电流：" + lasta1currnet + "A" + " B1相电流：" + lastb1currnet + "A" + "
            // C1相电流：" + lastc1currnet + "A" + " 负荷电流：" + lastd1currnet + "A");

            // float lasta1currnet = Integer.parseInt(str.substring(startIndex, startIndex
            // += 4), 16) / 100f;
            // float lastb1currnet = Integer.parseInt(str.substring(startIndex, startIndex
            // += 4), 16) / 100f;
            // float lastc1currnet = Integer.parseInt(str.substring(startIndex, startIndex
            // += 4), 16) / 100f;
            // float lastd1currnet = Integer.parseInt(str.substring(startIndex, startIndex
            // += 4), 16) / 100f;
            dc[addrint] = lastdcurrnet;
            int indexdcurrnetaddr = isnull(record.getlastdcurrentaddr());
            lastdcurrnet = dc[indexdcurrnetaddr];

            // 母线电流随1号
            // if(addrint == indexdcurrnetaddr){
            // dc = lastdcurrnet;
            // }else{
            // lastdcurrnet = dc;
            // }

            // lastacurrnet = lastacurrnet-0.5f;
            // lastbcurrnet = lastbcurrnet-0.5f;
            // lastccurrnet = lastccurrnet-0.5f;
            // 设置电流相关
            dlhlsensor.setLastacurrent(getCurrent(lastacurrnet, agreatevalue, alessvalue));
            dlhlsensor.setLastbcurrent(getCurrent(lastbcurrnet, bgreatevalue, blessvalue));
            dlhlsensor.setLastccurrent(getCurrent(lastccurrnet, cgreatevalue, clessvalue));
            dlhlsensor.setLastdcurrent(getDcurrent(lastdcurrnet, dgreatevalue, dlessvalue));
            dlhlsensor.setLastacurrentratio(lastacurrnet);
            dlhlsensor.setLastbcurrentratio(lastbcurrnet);
            dlhlsensor.setLastccurrentratio(lastccurrnet);
            dlhlsensor.setLastdcurrentratio(lastdcurrnet);
            // dlhlsensor.setLasta1current( getCurrent(lasta1currnet, a1greatevalue,
            // a1lessvalue));
            // dlhlsensor.setLastb1current( getCurrent(lastb1currnet, b1greatevalue,
            // b1lessvalue));
            // dlhlsensor.setLastc1current( getCurrent(lastc1currnet, c1greatevalue,
            // c1lessvalue));
            // dlhlsensor.setLastd1current( getDcurrent(lastd1currnet, dgreatevalue,
            // dlessvalue));
            AddAndUpdate(record, dlhlsensor);
        } else {
            setText("从设备返回的数据有误！请检查串口！");
        }
    }

    public void receiveDataJf(String str) {
        // 地址解析addr
        String addrstr = str.substring(2, 4);
        // 转地址
        Integer addrint = parseHex4(addrstr);
        reSend[addrint] = 0;
        // addrindex++;
        // dlhlserviceimpl.setstatus(0,addrint);
        reSend[parseHex4(addrstr)] = 0;
        // 设备类型编码
        String s_cid1 = str.substring(4, 6);
        String s_cid2 = str.substring(6, 8);
        // 请求返回状态00(正常）01 CHKSUM错
        String rtn = str.substring(8, 10);
        Integer startIndex = 28;
        // 判断请求返回，是否电流相关，返回码是否正常
        if ("80".equals(s_cid1) && ("40".equals(s_cid2) || "41".equals(s_cid2)) && "00".equals(rtn)) {
            setText("设备返回数据： 站点号：" + ad.getStationid() + " 设备组：" + ad.getDevicegroup() + " 设备地址：" + addrint);
            // String length = str.substring(12, 14);
            Dljfsensor dljf = new Dljfsensor();
            dljf.setStationid(ad.getStationid());
            dljf.setDevicegroup(ad.getDevicegroup());
            dljf.setDeviceaddr(addrint);
            Dljfsensor record = dljfsensorService.getModel(dljf);
            if (record == null) {
                setText("当前数据库无监测点：设备地址" + addrint + "的监测点" + " ！ 请先添加该监测点！");
                return;
            }
            // String stlyestr = record.getStyle();
            // if((stlyestr==null)||(stlyestr.equals("")))
            // {
            // stlyestr="adischarge|1|A相放电量,bdischarge|1|B相放电量,cdischarge|1|C相放电量,aphase|1|A相相位,bphase|1|B相相位,cphase|1|C相相位,areq|1|A相放电频次,breq|1|B相放电频次,creq|1|C相放电频次";
            // record.setStyle(stlyestr);
            // }
            float dischargecoefficientvalue = record.getCurrentcoefficientvalue() == null ? 1f
                    : record.getCurrentcoefficientvalue();
            Random ran = new Random();
            float fadischarge = parseHex88(str.substring(startIndex, startIndex += 2)) * dischargecoefficientvalue / 10;
            dljf.setLastadischarge(fadischarge); // A相放电量
            if (fadischarge != 0)
                dljf.setLastaphase((int) (ran.nextFloat() * 360));
            else
                dljf.setLastaphase(0);
            dljf.setLastareq(parseHex4(str.substring(startIndex, startIndex += 2)));// A相放电频次
            float fbdischarge = parseHex88(str.substring(startIndex, startIndex += 2)) * dischargecoefficientvalue / 10;
            dljf.setLastbdischarge(fbdischarge);
            ;// B 相放电量
            if (fbdischarge != 0)
                dljf.setLastbphase((int) (ran.nextFloat() * 360));
            else
                dljf.setLastbphase(0);
            dljf.setLastbreq(parseHex4(str.substring(startIndex, startIndex += 2)));// b相放电频次
            float fcdischarge = parseHex88(str.substring(startIndex, startIndex += 2)) * dischargecoefficientvalue / 10;
            dljf.setLastcdischarge(fcdischarge);
            ;// c相放电量
            if (fcdischarge != 0)
                dljf.setLastcphase((int) (ran.nextFloat() * 360));
            else
                dljf.setLastcphase(0);
            dljf.setLastcreq(parseHex4(str.substring(startIndex, startIndex += 2)));// c相放电频次
            // 母线电流随1号
            // if(addrint == 1){
            // dc = lastdcurrnet;
            // }else{
            // lastdcurrnet = dc;
            // }
            setText("A相放电量：" + dljf.getLastadischarge() + "pC A相放电频次：" + dljf.getLastareq() + " A相相位："
                    + dljf.getLastaphase() + "度");
            setText("B相放电量：" + dljf.getLastbdischarge() + "pC B相放电频次：" + dljf.getLastbreq() + " B相相位："
                    + dljf.getLastbphase() + "度");
            setText("C相放电量：" + dljf.getLastcdischarge() + "pC C相放电频次：" + dljf.getLastcreq() + " C相相位："
                    + dljf.getLastcphase() + "度");

            SensorData(record, dljf);
        } else {
            setText("从设备返回的数据有误！请检查串口！");
        }
    }

    @Transactional
    private void AddAndUpdate(Dlhlsensor record, Dlhlsensor dlhl) {
        int alarmLevel = 0;// 总报警等级
        String alarmMessage = "";// 报警消息
        // 获取数据库中的报警值相关
        if (record.getCurrentalarmvlaue() == null ||
                record.getCurrentalarmrelievevlaue() == null ||
                record.getCurrentwarnvlaue() == null ||
                record.getCurrentwarnrelievevlaue() == null ||
                record.getCurrentpercentagealarmvlaue() == null ||
                record.getCurrentpercentagealarmrelievevlaue() == null ||
                record.getCurrentpercentagewarnvlaue() == null ||
                record.getCurrentpercentagewarnrelievevlaue() == null ||
                record.getCoefficientalarmvlaue() == null ||
                record.getCoefficientalarmrelievevlaue() == null ||
                record.getCoefficientwarnvlaue() == null ||
                record.getCoefficientwarnrelievevlaue() == null) {
            setText("设备地址" + record.getDeviceaddr() + " 未设置报警值！");
            return;
        }
        // 电流报警值
        float currentalarmvlaue = record.getCurrentalarmvlaue();
        // 电流报警解除值
        float currentalarmrelievevlaue = record.getCurrentalarmrelievevlaue();
        // 电流预警值
        float currentwarnvlaue = record.getCurrentwarnvlaue();
        // 电流预警解除值
        float currentwarnrelievevlaue = record.getCurrentwarnrelievevlaue();
        // 电流比报警值
        float currentpercentagealarmvlaue = record.getCurrentpercentagealarmvlaue();
        // 电流比报警解除值
        float currentpercentagealarmrelievevlaue = record.getCurrentpercentagealarmrelievevlaue();
        // 电流比预警值
        float currentpercentagewarnvlaue = record.getCurrentpercentagewarnvlaue();
        // 电流比预警解除值
        float currentpercentagewarnrelievevlaue = record.getCurrentpercentagewarnrelievevlaue();
        // 不平衡系数报警值
        float coefficientalarmvlaue = record.getCoefficientalarmvlaue();
        // 不平衡系数报警解除值
        float coefficientalarmrelievevlaue = record.getCoefficientalarmrelievevlaue();
        // 不平衡系数预警值
        float coefficientwarnvlaue = record.getCoefficientwarnvlaue();
        // 不平衡系数预警解除值
        float coefficientwarnrelievevlaue = record.getCoefficientwarnrelievevlaue();

        // 报警逻辑
        float lastacurrent = dlhl.getLastacurrent();
        float lastbcurrent = dlhl.getLastbcurrent();
        float lastccurrent = dlhl.getLastccurrent();
        float lastdcurrent = dlhl.getLastdcurrent();
        // 报警逻辑
        // float lasta1current = dlhl.getLasta1current();
        // float lastb1current = dlhl.getLastb1current();
        // float lastc1current = dlhl.getLastc1current();
        // float lastd1current = dlhl.getLastd1current();
        // 获取最大电流值
        float maxcurrentvalue = Math.max(lastacurrent, lastbcurrent);
        maxcurrentvalue = Math.max(maxcurrentvalue, lastccurrent);
        // 获取最小电流值
        float mincurrentvalue = Math.min(lastacurrent, lastbcurrent);
        mincurrentvalue = Math.min(mincurrentvalue, lastccurrent);
        // 不平衡系数
        float currnetcoefficient;
        if (maxcurrentvalue == 0 || mincurrentvalue == 0) {
            currnetcoefficient = 0;
        } else {
            currnetcoefficient = Float.isNaN(maxcurrentvalue / mincurrentvalue) ? 0f
                    : (maxcurrentvalue / mincurrentvalue);
        }
        if (currnetcoefficient >= 3) {
            if (maxcurrentvalue <= 15) {
                currnetcoefficient = 2.f;
            }
        }
        // 电流比
        float acurrentpercentage;
        float bcurrentpercentage;
        float ccurrentpercentage;
        // 如果母线电流小于5a则不计算
        if (lastdcurrent <= 5f) {
            // 电流比置0 默认正常
            acurrentpercentage = 0f;
            bcurrentpercentage = 0f;
            ccurrentpercentage = 0f;
        } else {
            if (lastacurrent == 0f) {
                acurrentpercentage = 0f;
            } else {
                acurrentpercentage = lastacurrent / lastdcurrent * 100;
            }
            if (lastbcurrent == 0f) {
                bcurrentpercentage = 0f;
            } else {
                bcurrentpercentage = lastbcurrent / lastdcurrent * 100;
            }
            if (lastccurrent == 0f) {
                ccurrentpercentage = 0f;
            } else {
                ccurrentpercentage = lastccurrent / lastdcurrent * 100;
            }
        }
        // 定义电流报警状态值
        int acurrentstatus = GetAlarmStatus(lastacurrent, currentalarmvlaue, currentalarmrelievevlaue, currentwarnvlaue,
                currentwarnrelievevlaue, record.getLastaalarmstatus(), true, "A相电流", record.getDevicegroup(),
                record.getDeviceaddr(), record.getPointname());
        int bcurrentstatus = GetAlarmStatus(lastbcurrent, currentalarmvlaue, currentalarmrelievevlaue, currentwarnvlaue,
                currentwarnrelievevlaue, record.getLastbalarmstatus(), true, "B相电流", record.getDevicegroup(),
                record.getDeviceaddr(), record.getPointname());
        int ccurrentstatus = GetAlarmStatus(lastccurrent, currentalarmvlaue, currentalarmrelievevlaue, currentwarnvlaue,
                currentwarnrelievevlaue, record.getLastcalarmstatus(), true, "C相电流", record.getDevicegroup(),
                record.getDeviceaddr(), record.getPointname());

        // 定义电流比报警状态值
        int acurrentpercentagestatus = GetAlarmStatus(acurrentpercentage, currentpercentagealarmvlaue,
                currentpercentagealarmrelievevlaue, currentpercentagewarnvlaue, currentpercentagewarnrelievevlaue,
                record.getLastaralarmstatus(), true, "A相电流比", record.getDevicegroup(), record.getDeviceaddr(),
                record.getPointname());
        int bcurrentpercentagestatus = GetAlarmStatus(bcurrentpercentage, currentpercentagealarmvlaue,
                currentpercentagealarmrelievevlaue, currentpercentagewarnvlaue, currentpercentagewarnrelievevlaue,
                record.getLastbralarmstatus(), true, "B相电流比", record.getDevicegroup(), record.getDeviceaddr(),
                record.getPointname());
        int ccurrentpercentagestatus = GetAlarmStatus(ccurrentpercentage, currentpercentagealarmvlaue,
                currentpercentagealarmrelievevlaue, currentpercentagewarnvlaue, currentpercentagewarnrelievevlaue,
                record.getLastcralarmstatus(), true, "C相电流比", record.getDevicegroup(), record.getDeviceaddr(),
                record.getPointname());
        // 定义三相不平衡系数报警值
        int currentcoefficientstatus = GetAlarmStatus(currnetcoefficient, coefficientalarmvlaue,
                coefficientalarmrelievevlaue, coefficientwarnvlaue, coefficientwarnrelievevlaue,
                record.getLastabcalarmstatus(), true, "三相不平衡系数", record.getDevicegroup(), record.getDeviceaddr(),
                record.getPointname());

        // 设置报警状态
        dlhl.setLastaalarmstatus(acurrentstatus);
        dlhl.setLastbalarmstatus(bcurrentstatus);
        dlhl.setLastcalarmstatus(ccurrentstatus);
        dlhl.setLastaralarmstatus(acurrentpercentagestatus);
        dlhl.setLastbralarmstatus(bcurrentpercentagestatus);
        dlhl.setLastcralarmstatus(ccurrentpercentagestatus);
        dlhl.setLastabcalarmstatus(currentcoefficientstatus);
        // 设置电流系数
        dlhl.setLastcoefficient(Float.isNaN(currnetcoefficient) ? 0f : currnetcoefficient);
        dlhl.setLastalarmmessage(GetAlarmMessage(acurrentstatus, "A相电流") +
                GetAlarmMessage(bcurrentstatus, "B相电流") +
                GetAlarmMessage(ccurrentstatus, "C相电流") +
                GetAlarmMessage(acurrentpercentagestatus, "A相A/R") +
                GetAlarmMessage(bcurrentpercentagestatus, "B相A/R") +
                GetAlarmMessage(ccurrentpercentagestatus, "C相A/R") +
                GetAlarmMessage(currentcoefficientstatus, "三相不平衡系数"));
        // 获取最大电流值
        // float maxcurrent1value = Math.max(lasta1current, lastb1current);
        // maxcurrent1value = Math.max(maxcurrent1value, lastc1current);
        // //获取最小电流值
        // float mincurrent1value = Math.min(lasta1current, lastb1current);
        // mincurrent1value = Math.min(mincurrent1value, lastc1current);
        // //不平衡系数
        // float currnet1coefficient;
        // if(maxcurrent1value==0||mincurrent1value==0){
        // currnet1coefficient = 0;
        // }else{
        // currnet1coefficient = Float.isNaN(maxcurrent1value / mincurrent1value) ? 0f :
        // (maxcurrent1value / mincurrent1value);
        // }
        // //电流比
        // float a1currentpercentage;
        // float b1currentpercentage;
        // float c1currentpercentage;
        // //判断母线电流,如果为0 则默认正常
        // if(lastd1current<=5f){
        // a1currentpercentage = 0f;
        // b1currentpercentage = 0f;
        // c1currentpercentage = 0f;
        // }else{
        // if(lasta1current==0f){
        // a1currentpercentage=0f;
        // }else{
        // a1currentpercentage = lasta1current / lastd1current * 100;
        // }
        // if(lastb1current==0f){
        // b1currentpercentage=0f;
        // }else{
        // b1currentpercentage = lastb1current / lastd1current * 100;
        // }
        // if(lastc1current==0f){
        // c1currentpercentage=0f;
        // }else{
        // c1currentpercentage = lastc1current / lastd1current * 100;
        // }
        // }
        // 定义电流报警状态值
        // int a1currentstatus = GetAlarmStatus(lasta1current, currentalarmvlaue,
        // currentalarmrelievevlaue, currentwarnvlaue, currentwarnrelievevlaue,
        // record.getLasta1alarmstatus(), true, "A1相电流", record.getDeviceaddr(),
        // record.getPointname());
        // int b1currentstatus = GetAlarmStatus(lastb1current, currentalarmvlaue,
        // currentalarmrelievevlaue, currentwarnvlaue, currentwarnrelievevlaue,
        // record.getLastb1alarmstatus(), true, "B1相电流", record.getDeviceaddr(),
        // record.getPointname());
        // int c1currentstatus = GetAlarmStatus(lastc1current, currentalarmvlaue,
        // currentalarmrelievevlaue, currentwarnvlaue, currentwarnrelievevlaue,
        // record.getLastc1alarmstatus(), true, "C1相电流", record.getDeviceaddr(),
        // record.getPointname());
        // 定义电流比报警状态值
        // int a1currentpercentagestatus = GetAlarmStatus(a1currentpercentage,
        // currentpercentagealarmvlaue, currentpercentagealarmrelievevlaue,
        // currentpercentagewarnvlaue, currentpercentagewarnrelievevlaue,
        // record.getLastar1alarmstatus(), true, "A1相电流比", record.getDeviceaddr(),
        // record.getPointname());
        // int b1currentpercentagestatus = GetAlarmStatus(b1currentpercentage,
        // currentpercentagealarmvlaue, currentpercentagealarmrelievevlaue,
        // currentpercentagewarnvlaue, currentpercentagewarnrelievevlaue,
        // record.getLastbr1alarmstatus(), true, "B1相电流比", record.getDeviceaddr(),
        // record.getPointname());
        // int c1currentpercentagestatus = GetAlarmStatus(c1currentpercentage,
        // currentpercentagealarmvlaue, currentpercentagealarmrelievevlaue,
        // currentpercentagewarnvlaue, currentpercentagewarnrelievevlaue,
        // record.getLastcr1alarmstatus(), true, "C1相电流比", record.getDeviceaddr(),
        // record.getPointname());
        // 定义三相不平衡系数报警值
        // int current1coefficientstatus = GetAlarmStatus(currnet1coefficient,
        // coefficientalarmvlaue, coefficientalarmrelievevlaue, coefficientwarnvlaue,
        // coefficientwarnrelievevlaue, record.getLastabc1alarmstatus(), true,
        // "三相1不平衡系数", record.getDeviceaddr(), record.getPointname());
        // 设置报警状态
        // dlhl.setLasta1alarmstatus(acurrentstatus);
        // dlhl.setLastb1alarmstatus(bcurrentstatus);
        // dlhl.setLastc1alarmstatus(ccurrentstatus);
        // dlhl.setLastar1alarmstatus(acurrentpercentagestatus);
        // dlhl.setLastbr1alarmstatus(bcurrentpercentagestatus);
        // dlhl.setLastcr1alarmstatus(ccurrentpercentagestatus);
        // dlhl.setLastabc1alarmstatus(currentcoefficientstatus);
        // //设置电流系数
        // dlhl.setLastcoefficient1(Float.isNaN(currnet1coefficient) ? 0f :
        // currnet1coefficient);
        // dlhl.setLastalarmmessage(dlhl.getLastalarmmessage()+
        // GetAlarmMessage(a1currentstatus, "A1相电流") +
        // GetAlarmMessage(b1currentstatus, "B1相电流") +
        // GetAlarmMessage(c1currentstatus, "C1相电流") +
        // GetAlarmMessage(a1currentpercentagestatus, "A1相A/R") +
        // GetAlarmMessage(b1currentpercentagestatus, "B1相A/R") +
        // GetAlarmMessage(c1currentpercentagestatus, "C1相A/R") +
        // GetAlarmMessage(current1coefficientstatus, "三相1不平衡系数")
        // );
        int[] status_arr = { dlhl.getLastaalarmstatus(), dlhl.getLastbalarmstatus(), dlhl.getLastcalarmstatus(),
                dlhl.getLastaralarmstatus(), dlhl.getLastbralarmstatus(), dlhl.getLastcralarmstatus(),
                dlhl.getLastabcalarmstatus(),
                // dlhl.getLasta1alarmstatus(), dlhl.getLastb1alarmstatus(),
                // dlhl.getLastc1alarmstatus(),
                // dlhl.getLastar1alarmstatus(), dlhl.getLastbr1alarmstatus(),
                // dlhl.getLastcr1alarmstatus(),dlhl.getLastabc1alarmstatus(),
        };
        dlhl.setStyle(record.getStyle());
        // 设置总报警等级
        dlhl.setLastalarmlevel(MAX(status_arr));
        dlhl.setLastcommunicationstatus(0);
        dlhl.setLastdatatime(new Date());
        dlhl.setPointname(record.getPointname());
        dlhl.setLasthisdatatime(addHistory(record));

        if (dlhlserviceimpl.Update(dlhl, false) == 0) {
            setText("更新实时数据失败，请检查数据库连接");
        }
    }

    /**
     * 判断电流大小并与系数计算返回校正后的电流
     *
     * @param current
     * @param greateValue
     * @param lessValue
     * @return
     */
    public float getCurrent(float current, float greateValue, float lessValue) {
        float value = current;
        // current = current-0.5f;
        if (current >= 10) {
            value = current * greateValue;
        } else if (current < 10) {
            value = current * lessValue;
        }
        return Float.isNaN(value) ? 0f : value;
    }

    private Float getDcurrent(float current, float greateValue, float lessValue) {
        float value = current;
        if (current >= 180) {
            value = current * greateValue;
        } else if (current < 180) {
            value = current * lessValue;
        }
        return Float.isNaN(value) ? 0f : value;
    }

    private Date addHistory(Dlhlsensor sensor) {
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Dlhlsensor sensor) {
        Dlhlhistory his = new Dlhlhistory();
        his.setDeviceaddr(sensor.getDeviceaddr());
        his.setdcurrentaddr(sensor.getlastdcurrentaddr());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setA1current(sensor.getLasta1current());
        his.setAcurrent(sensor.getLastacurrent());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        his.setAlarmmessage(sensor.getLastalarmmessage());
        his.setB1current(sensor.getLastb1current());
        his.setBcurrent(sensor.getLastbcurrent());
        his.setC1current(sensor.getLastc1current());
        his.setCcurrent(sensor.getLastccurrent());
        his.setCoefficient(sensor.getLastcoefficient());
        his.setCoefficient1(sensor.getLastcoefficient1());
        his.setD1current(sensor.getLastd1current());
        his.setDatatime(sensor.getLastdatatime());
        his.setDcurrent(sensor.getLastdcurrent());
        his.setPointname(sensor.getPointname());
        his.setStationid(sensor.getStationid());
        his.setAalarmstatus(sensor.getLastaalarmstatus());
        his.setBalarmstatus(sensor.getLastbalarmstatus());
        his.setCalarmstatus(sensor.getLastcalarmstatus());
        his.setA1alarmstatus(sensor.getLasta1alarmstatus());
        his.setB1alarmstatus(sensor.getLastb1alarmstatus());
        his.setC1alarmstatus(sensor.getLastc1alarmstatus());
        dlhlserviceimpl.Add(his);
    }

    private void SensorData(Dljfsensor dljf, Dljfsensor dljfsensor) {
        int alarmLevel = 0;// 报警等级
        String alarmMessage = "";// 报警消息
        if (dljf.getAdischargealarmvalue() == null ||
                dljf.getAdischargealarmrelievevalue() == null ||
                dljf.getAdischargewarnvalue() == null ||
                dljf.getAdischargewarnrelievevalue() == null /*
                                                              * ||
                                                              * dljf.getAreqwarnvalue() == null||
                                                              * dljf.getAreqwarnrelievevalue() == null ||
                                                              * dljf.getAreqalarmrelievevalue() == null ||
                                                              * dljf.getAreqalarmvalue() == null ||
                                                              * dljf.getAphasealarmvalue() == null ||
                                                              * dljf.getAphasealarmrelievevalue() == null ||
                                                              * dljf.getAphasewarnvalue() == null ||
                                                              * dljf.getAphasewarnrelievevalue() == null
                                                              */
        ) {
            setText("设备地址" + dljf.getDeviceaddr() + " 未设置报警值！");
            return;
        }
        List<Integer> array = new ArrayList<>();
        dljfsensor.setLastadischargealarmstatus(
                GetAlarmStatus(isnull(dljfsensor.getLastadischarge()), isnull(dljf.getAdischargealarmvalue()),
                        isnull(dljf.getAdischargealarmrelievevalue()), isnull(dljf.getAdischargewarnvalue()),
                        isnull(dljf.getAdischargewarnrelievevalue()),
                        isnull(dljf.getLastadischargealarmstatus()), true, "A相放电量", dljf.getDevicegroup(),
                        dljf.getDeviceaddr(), dljf.getPointname()));
        alarmMessage += GetAlarmMessage(dljfsensor.getLastadischargealarmstatus(), "A相放电量");
        array.add(dljfsensor.getLastadischargealarmstatus());
        dljfsensor.setLastbdischargealarmstatus(
                GetAlarmStatus(isnull(dljfsensor.getLastbdischarge()), isnull(dljf.getAdischargealarmvalue()),
                        isnull(dljf.getAdischargealarmrelievevalue()), isnull(dljf.getAdischargewarnvalue()),
                        isnull(dljf.getAdischargewarnrelievevalue()),
                        isnull(dljf.getLastbdischargealarmstatus()), true, "B相放电量", dljf.getDevicegroup(),
                        dljf.getDeviceaddr(), dljf.getPointname()));
        alarmMessage += GetAlarmMessage(dljfsensor.getLastbdischargealarmstatus(), "B相放电量");
        array.add(dljfsensor.getLastbdischargealarmstatus());
        dljfsensor.setLastcdischargealarmstatus(
                GetAlarmStatus(isnull(dljfsensor.getLastcdischarge()), isnull(dljf.getAdischargealarmvalue()),
                        isnull(dljf.getAdischargealarmrelievevalue()), isnull(dljf.getAdischargewarnvalue()),
                        isnull(dljf.getAdischargewarnrelievevalue()),
                        isnull(dljf.getLastcdischargealarmstatus()), true, "C相放电量", dljf.getDevicegroup(),
                        dljf.getDeviceaddr(), dljf.getPointname()));
        alarmMessage += GetAlarmMessage(dljfsensor.getLastcdischargealarmstatus(), "C相放电量");
        array.add(dljfsensor.getLastcdischargealarmstatus());
        // dljfsensor.setLasta1dischargealarmstatus(GetAlarmStatus(isnull(dljfsensor.getLasta1discharge()),
        // isnull(dljf.getAdischargealarmvalue()),
        // isnull(dljf.getAdischargealarmrelievevalue()),
        // isnull(dljf.getAdischargewarnvalue()),
        // isnull(dljf.getAdischargewarnrelievevalue()),
        // isnull(dljf.getLasta1dischargealarmstatus()),
        // true,"A1相放电量",dljf.getDeviceaddr(), dljf.getPointname()));
        // alarmMessage += GetAlarmMessage(dljfsensor.getLasta1dischargealarmstatus(),
        // "A1相放电量");
        // array.add(dljfsensor.getLasta1dischargealarmstatus());
        // dljfsensor.setLastb1dischargealarmstatus(GetAlarmStatus(isnull(dljfsensor.getLastb1discharge()),
        // isnull(dljf.getAdischargealarmvalue()),
        // isnull(dljf.getAdischargealarmrelievevalue()),
        // isnull(dljf.getAdischargewarnvalue()),
        // isnull(dljf.getAdischargewarnrelievevalue()),
        // isnull(dljf.getLastb1dischargealarmstatus()),
        // true,"B1相放电量",dljf.getDeviceaddr(), dljf.getPointname()));
        // alarmMessage += GetAlarmMessage(dljfsensor.getLastb1dischargealarmstatus(),
        // "B1相放电量");
        // array.add(dljfsensor.getLastb1dischargealarmstatus());
        // dljfsensor.setLastc1dischargealarmstatus(GetAlarmStatus(isnull(dljfsensor.getLastc1discharge()),
        // isnull(dljf.getAdischargealarmvalue()),
        // isnull(dljf.getAdischargealarmrelievevalue()),
        // isnull(dljf.getAdischargewarnvalue()),
        // isnull(dljf.getAdischargewarnrelievevalue()),
        // isnull(dljf.getLastc1dischargealarmstatus()),
        // true,"C1相放电量",dljf.getDeviceaddr(), dljf.getPointname()));
        // alarmMessage += GetAlarmMessage(dljfsensor.getLastc1dischargealarmstatus(),
        // "C1相放电量");
        // array.add(dljfsensor.getLastc1dischargealarmstatus());
        /*
         * dljfsensor.setLastareqalarmstatus(GetAlarmStatus(isnull(dljfsensor.
         * getLastareq()), isnull(dljf.getAreqalarmvalue()),
         * isnull(dljf.getAreqalarmrelievevalue()), isnull(dljf.getAreqwarnvalue()),
         * isnull(dljf.getAreqwarnrelievevalue()),
         * isnull(dljf.getLastareqalarmstatus()), true,"A相放电频次",dljf.getDeviceaddr(),
         * dljf.getPointname()));
         * 
         * dljfsensor.setLastbreqalarmstatus(GetAlarmStatus(isnull(dljfsensor.
         * getLastbreq()), isnull(dljf.getAreqalarmvalue()),
         * isnull(dljf.getAreqalarmrelievevalue()),
         * isnull(dljfsensor.getAreqwarnvalue()),
         * isnull(dljf.getAreqwarnrelievevalue()),
         * isnull(dljf.getLastbreqalarmstatus()), true,"B相放电频次",dljf.getDeviceaddr(),
         * dljf.getPointname()));
         * 
         * dljfsensor.setLastcreqalarmstatus(GetAlarmStatus(isnull(dljfsensor.
         * getLastcreq()), isnull(dljf.getAreqalarmvalue()),
         * isnull(dljf.getAreqalarmrelievevalue()), isnull(dljf.getAreqwarnvalue()),
         * isnull(dljf.getAreqwarnrelievevalue()),
         * isnull(dljf.getLastcreqalarmstatus()), true,"C相放电频次",dljf.getDeviceaddr(),
         * dljf.getPointname()));
         * 
         * dljfsensor.setLastaphasealarmstatus(GetAlarmStatus(isnull(dljfsensor.
         * getLastaphase()), isnull(dljf.getAphasealarmvalue()),
         * isnull(dljf.getAphasealarmrelievevalue()), isnull(dljf.getAphasewarnvalue()),
         * isnull(dljf.getAphasewarnrelievevalue()),
         * isnull(dljf.getLastaphasealarmstatus()), true,"A相相位",dljf.getDeviceaddr(),
         * dljf.getPointname()));
         * 
         * dljfsensor.setLastbphasealarmstatus(GetAlarmStatus(isnull(dljfsensor.
         * getLastbphase()), isnull(dljf.getAphasealarmvalue()),
         * isnull(dljf.getAphasealarmrelievevalue()), isnull(dljf.getAphasewarnvalue()),
         * isnull(dljf.getAphasewarnrelievevalue()),
         * isnull(dljf.getLastbphasealarmstatus()), true,"B相相位",dljf.getDeviceaddr(),
         * dljf.getPointname()));
         * 
         * dljfsensor.setLastcphasealarmstatus(GetAlarmStatus(isnull(dljfsensor.
         * getLastcphase()), isnull(dljf.getAphasealarmvalue()),
         * isnull(dljf.getAphasealarmrelievevalue()), isnull(dljf.getAphasewarnvalue()),
         * isnull(dljf.getAphasewarnrelievevalue()),
         * isnull(dljf.getLastcphasealarmstatus()), true,"C相相位",dljf.getDeviceaddr(),
         * dljf.getPointname()));
         * 
         * dljfsensor.setLastalarmmessage(
         * GetAlarmMessage(dljfsensor.getLastadischargealarmstatus(),"A相放电量")+
         * GetAlarmMessage(dljfsensor.getLastbdischargealarmstatus(),"B相放电量")+
         * GetAlarmMessage(dljfsensor.getLastcdischargealarmstatus(),"C相放电量")
         * 
         * GetAlarmMessage(dljf.getLastareqalarmstatus(),"A相频次")+
         * GetAlarmMessage(dljf.getLastbreqalarmstatus(),"B相频次")+
         * GetAlarmMessage(dljf.getLastcreqalarmstatus(),"C相频次")+
         * 
         * GetAlarmMessage(dljf.getLastaphasealarmstatus(),"A相相位")+
         * GetAlarmMessage(dljf.getLastbphasealarmstatus(),"B相相位")+
         * GetAlarmMessage(dljf.getLastcphasealarmstatus(),"C相相位"));
         * int[] status_arr = {dljfsensor.getLastadischargealarmstatus(),
         * dljfsensor.getLastbdischargealarmstatus(),dljfsensor.
         * getLastcdischargealarmstatus()
         * dljfsensor.getLastareqalarmstatus(),dljfsensor.getLastbreqalarmstatus(),
         * dljfsensor.getLastcreqalarmstatus(),dljfsensor.getLastaphasealarmstatus(),
         * dljfsensor.getLastbphasealarmstatus(),
         * dljfsensor.getLastcphasealarmstatus()
         */
        dljfsensor.setStyle(dljf.getStyle());
        alarmLevel = HexUtil.MAX(array);
        dljfsensor.setLastalarmlevel(alarmLevel);
        dljfsensor.setLastalarmmessage(alarmMessage);
        dljfsensor.setLastcommunicationstatus(0);
        dljfsensor.setLastdatatime(new Date());
        dljfsensor.setLasthisdatatime(addHistory(dljf));
        if (dljfsensorService.Update(dljfsensor, false) == 0) {
            setText("更新实时数据失败，请检查数据库连接");
        }
    }

    private Date addHistory(Dljfsensor sensor) {
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Dljfsensor sensor) {
        Dljfhistory his = new Dljfhistory();
        his.setDeviceaddr(sensor.getDeviceaddr());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        his.setAlarmmessage(sensor.getLastalarmmessage());
        his.setDatatime(sensor.getLastdatatime());
        his.setPointname(sensor.getPointname());
        his.setStationid(sensor.getStationid());
        his.setCommunicationstatus(sensor.getLastcommunicationstatus());
        // 需要添加自己定义的属性
        // 频次
        his.setAreq(sensor.getLastareq());
        his.setBreq(sensor.getLastbreq());
        his.setCreq(sensor.getLastcreq());
        // his.setA1req(sensor.getLasta1req());
        // his.setB1req(sensor.getLastb1req());
        // his.setC1req(sensor.getLastc1req());
        // 相位
        his.setAphase(sensor.getLastaphase());
        his.setBphase(sensor.getLastbphase());
        his.setCphase(sensor.getLastcphase());
        // his.setA1phase(sensor.getLasta1phase());
        // his.setB1phase(sensor.getLastb1phase());
        // his.setC1phase(sensor.getLastc1phase());
        // 放电量
        his.setAdischarge(sensor.getLastadischarge());
        his.setBdischarge(sensor.getLastbdischarge());
        his.setCdischarge(sensor.getLastcdischarge());

        // his.setA1discharge(sensor.getLasta1discharge());
        // his.setB1discharge(sensor.getLastb1discharge());
        // his.setC1discharge(sensor.getLastc1discharge());
        // 报警状态

        /*
         * his.setAreqalarmstatus(sensor.getLastareqalarmstatus());
         * his.setBreqalarmstatus(sensor.getLastbreqalarmstatus());
         * his.setCreqalarmstatus(sensor.getLastcreqalarmstatus());
         */

        his.setAdischargealarmstatus(sensor.getLastadischargealarmstatus());
        his.setBdischargealarmstatus(sensor.getLastbdischargealarmstatus());
        his.setCdischargealarmstatus(sensor.getLastcdischargealarmstatus());

        // his.setA1dischargealarmstatus(sensor.getLasta1dischargealarmstatus());
        // his.setB1dischargealarmstatus(sensor.getLastb1dischargealarmstatus());
        // his.setC1dischargealarmstatus(sensor.getLastc1dischargealarmstatus());
        /*
         * his.setAphasealarmstatus(sensor.getLastaphasealarmstatus());
         * his.setBphasealarmstatus(sensor.getLastbphasealarmstatus());
         * his.setCphasealarmstatus(sensor.getLastcphasealarmstatus());
         */

        dljfsensorService.Add(his);
    }

    public static float parseHex88(String num) {
        int ret = Integer.parseInt(num, 16);
        if (num.length() == 2) {
            return ret;
        } else if (num.length() == 4) {
            ret = ((ret & 0x8000) > 0) ? (ret - 0x10000) : (ret);
            return ret;
        } else {
            throw new NumberFormatException("Wrong length: " + num.length() + ", must be 4.");
        }
    }

    @Override
    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {
        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        String cmdtype = "";
        String nametype = "";
        int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
        while (issend.get(Thread.currentThread().getId()) != null) {
            if (isrun) {
                if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                    addrindex = Appdevice.getAddrmin();
                cstr = String.format(Appdevice.getCmd(), String.format("%02X", addrindex));
                Send(cstr);
                reSend[addrindex]++;
                if (reSend[addrindex] > 3) {
                    dlhlserviceimpl.UpdateStatus(ad, addrindex, 1);
                    reSend[addrindex] = 0;
                    addrindex++;
                }
            } else if (rescode != 0) {
                setText(resmsg[rescode]);
            }
            Thread.sleep(timersp);
        }
    }
}
